package cn.org.theo.service.impl;

import cn.org.theo.mapper.*;
import cn.org.theo.pojo.*;
import cn.org.theo.service.ConsultantService;
import cn.org.theo.vo.*;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * project name: IntelliJ IDEA
 * Date: 2022/8/24 21:19
 *
 * @PackageName: cn.org.theo.service.impl
 * @ClassName: ConsultantServiceImpl
 * @Author: Theo
 * @Version:
 * @Description:
 */
@Service
public class ConsultantServiceImpl implements ConsultantService {

    @Autowired
    private ConsultantMapper consultantMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private JournalMapper journalMapper;
    @Autowired
    private ConfigureMapper configureMapper;

    @Autowired
    private ConsultantFieldMapper consultantFieldMapper;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Override
    public Result showPositionTitle() {
        List<Consultant> consultants =
                consultantMapper.queryPositionalTitles();
        Set<Consultant> set = new HashSet<>();
        consultants.forEach(t->set.add(t));
        return new Result(0,"获取职称成功",set);
    }

    @Override
    public Result query(ConsultantVo consultantVo,int pageNo) {
        Map<String,Object> map = new HashMap<>();
        if (consultantVo.getStatus() == 1){
            if (consultantVo.getName() != null || "".equals(consultantVo.getName())){
                map.put("name","%" + consultantVo.getName() + "%");
            }else {
                map.put("name","");
            }
            map.put("positionalTitles",consultantVo.getPositionalTitles());
            map.put("status",consultantVo.getStatus());
            map.put("limit",(pageNo - 1) * 5);
            map.put("offset",5);
            List<ConsultantVo> consultants = consultantMapper.queryForConditionByPage(map);

            Page<ConsultantVo> page = new Page();
            page.setPageNo(pageNo);
            page.setLimit((pageNo - 1) * 5);
            page.setOffset(5);
            page.setList(consultants);
            if (consultantVo.getName() != null || "".equals(consultantVo.getName())){
                consultantVo.setName("%"+consultantVo.getName()+"%");
            }else {
                consultantVo.setName("");
            }
            page.setTotalCount(consultantMapper.queryTotalCount(consultantVo));
            System.out.println(page.getTotalCount());
            int totalCount = page.getTotalCount();
            page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
            if (page.getTotalPageCount() == 0) {
                page.setCurrentPage(0);
            }

            return Result.updateResp(1,"数据获取成功","数据获取失败",page);
        }else{
            if (consultantVo.getName() != null || "".equals(consultantVo.getName())){
                map.put("name","%" + consultantVo.getName() + "%");
            }else {
                map.put("name","");
            }
            map.put("positionalTitles",consultantVo.getPositionalTitles());
            map.put("status",1);
            map.put("limit",(pageNo - 1) * 5);
            map.put("offset",5);
            List<ConsultantVo> consultants = consultantMapper.queryForConditionByPage2(map);

            Page<ConsultantVo> page = new Page();
            page.setPageNo(pageNo);
            page.setLimit((pageNo - 1) * 5);
            page.setOffset(5);
            page.setList(consultants);
            if (consultantVo.getName() != null || "".equals(consultantVo.getName())){
                consultantVo.setName("%"+consultantVo.getName()+"%");
            }else {
                consultantVo.setName("");
            }
            page.setTotalCount(consultantMapper.queryTotalCount(consultantVo));
            System.out.println(page.getTotalCount());
            int totalCount = page.getTotalCount();
            page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
            if (page.getTotalPageCount() == 0) {
                page.setCurrentPage(0);
            }

            return Result.updateResp(1,"数据获取成功","数据获取失败",page);
        }
    }
    @Override
    public Result updateStatus(ConsultantVo consultantVo, String username) {

        //查询manager_id
        Manager manager = consultantMapper.query(consultantVo);
        Manager query = managerMapper.query(manager);
        if (query.getStatus() == 1){
            query.setStatus(3);
        }else{
            query.setStatus(1);
        }
        int i = managerMapper.update(query);

        //插入操作日志
        Journal journal = new Journal();
        journal.setUserId(manager.getId());
        //时间
        long l = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        journal.setTime(sdf.format(l));
        //操作
        journal.setOption(query.getStatus() == 1 ? "启用用户" + query.getUsername() : "禁用用户" + query.getUsername());

        journalMapper.add(journal);

        return Result.updateResp(i,"状态修改成功","状态修改失败",null);
    }

    @Override
    public Result del(int id, String username) {
        ConsultantVo consultantVo = new ConsultantVo();
        consultantVo.setId(id);
        Manager manager = consultantMapper.query(consultantVo);
        manager.setStatus(2);
        int i = managerMapper.update(manager);

        //插入操作日志
        if (username != null){
            Journal journal = new Journal();
            journal.setUserId(manager.getId());
            long l = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            journal.setTime(sdf.format(l));
            journal.setOption("删除用户id为" + id);
            journalMapper.add(journal);
        }
        return Result.updateResp(i,"删除成功","删除失败",null);
    }

    @Override
    public Result updatePwd(int id, String username) {
        ConsultantVo consultant = new ConsultantVo();
        consultant.setId(id);
        Manager manager = consultantMapper.query(consultant);
        //获取参数表默认密码
        Configure configure = new Configure();
        configure.setKeyp("password");
        Configure configure1 = configureMapper.queryForOne(configure);
        manager.setPassword(configure1.getValue());
        System.out.println(manager);
        int update = managerMapper.update(manager);
        //插入操作日志
        if (username != null) {
            manager.setUsername(username);
            Journal journal = new Journal();
            journal.setUserId(manager.getId());

            long l = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            journal.setTime(sdf.format(l));

            journal.setOption("id为" + id + "用户重置密码");

            journalMapper.add(journal);
        }
        return Result.updateResp(update, "重置密码成功", "重置密码失败", null);
    }

    @Override
    public Result addAdmin(Consultant consultant) {
        //获取manager最大id；
        int maxNum = managerMapper.getMaxNum();
        //name设置为tea + 最大id
        Manager manager = new Manager();
        maxNum++;

        //密码为654321
        Configure configure = new Configure();
        configure.setKeyp("password");
        manager.setPassword(configureMapper.queryForOne(configure).getValue());
        //状态设置为1，角色根据参数判断
        manager.setStatus(1);
        if (consultant.getName() == null ||"".equals(consultant.getName())){
            //添加管理员
            manager.setRole(1);
            manager.setUsername("admin" + maxNum);
            int i1 = managerMapper.insert(manager);
        }else{
            //添加咨询师
            manager.setRole(2);
            manager.setUsername("tea" + maxNum);
            //将manager插入数据库
            int i1 = managerMapper.insert(manager);
            //将后台管理员信息插入后台consultant表
            consultant.setManagerId(manager.getId());
            int i = consultantMapper.insert(consultant);
        }



        return Result.updateResp(1,"添加成功","",null);
    }



    @Override
    public Result queryByFront(String fieldNameList, String consName, Integer pageNo) {
        List<FieldNameVo> fieldNameVos = JSON.parseArray(fieldNameList, FieldNameVo.class);
        System.out.println(fieldNameVos);
        if (fieldNameVos.size() == 0){
            Map<String,Object> map = new HashMap<>();
            map.put("name","%"+consName+"%");
            map.put("status",1);
            map.put("limit",(pageNo - 1) * 5);
            map.put("offset",5);
            List<ConsultantFrontVo> consultantVos = consultantMapper.queryByFront(map);
            //获取领域
            for (ConsultantFrontVo vo : consultantVos) {
                List<ConsultantFieldVo> query = consultantFieldMapper.query(vo.getId());
                vo.setConsultantFieldVos(query);
            }
            Page<ConsultantFrontVo> page = new Page();
            page.setPageNo(pageNo);
            page.setLimit((pageNo - 1) * 5);
            page.setOffset(5);
            page.setList(consultantVos);
            page.setTotalCount(consultantMapper.queryTotalCountFront(map));
            System.out.println(page.getTotalCount());
            int totalCount = page.getTotalCount();
            page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
            if (page.getTotalPageCount() == 0) {
                page.setCurrentPage(0);
            }
            consultantVos.forEach(System.out::println);
            return Result.updateResp(1,"数据获取成功","",page);
        }else{
            //获取领域id
            List<String> fieldNames = new ArrayList<>();
            fieldNameVos.forEach(t->fieldNames.add(t.getFieldName()));
            List<Field> fields = fieldMapper.queryId(fieldNames);

            //获取咨询师id（去重）
            List<Integer> fieldId = new ArrayList<>();
            fields.forEach(t->fieldId.add(t.getId()));
            List<Integer> consIds = consultantFieldMapper.queryId(fieldId);

            //获取咨询师数据
            Map<String,Object> map = new HashMap<>();
            map.put("name","%"+consName+"%");
            map.put("status",1);
            map.put("limit",(pageNo - 1) * 5);
            map.put("offset",5);
            map.put("list",consIds);
            List<ConsultantFrontVo> consultantVos = consultantMapper.queryByFront(map);
            //获取领域
            for (ConsultantFrontVo vo : consultantVos) {
                List<ConsultantFieldVo> query = consultantFieldMapper.query(vo.getId());
                vo.setConsultantFieldVos(query);
            }
            Page<ConsultantFrontVo> page = new Page();
            page.setPageNo(pageNo);
            page.setLimit((pageNo - 1) * 5);
            page.setOffset(5);
            page.setList(consultantVos);
            page.setTotalCount(consultantMapper.queryTotalCountFront(map));
            System.out.println(page.getTotalCount());
            int totalCount = page.getTotalCount();
            page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
            if (page.getTotalPageCount() == 0) {
                page.setCurrentPage(0);
            }
            consultantVos.forEach(System.out::println);
            return Result.updateResp(1,"数据获取成功","",page);
        }
    }

    @Override
    public Result timeInfo(int consId) {
        //通过用户id获取manager_id
        ConsultantVo consultantVo = new ConsultantVo();
        consultantVo.setId(consId);
        Manager query = consultantMapper.query(consultantVo);
        //通过manager_id获取日期时间列表
        List<ScheduleVo> scheduleList = scheduleMapper.query(query);

        List<DateTimeVo> dateTimeList = new ArrayList<>();

        for (ScheduleVo scheduleVo : scheduleList) {
            DateTimeVo dateTimeVo = new DateTimeVo();
            String[] s = scheduleVo.getDateTime().split(" ");
            String date = s[0];
            String slot = scheduleVo.getSlot();
            String[] split = slot.split(":");
            String time = split[0];
            String dateTime = date + "-" + time;
            dateTimeVo.setDateTime(dateTime);
            dateTimeList.add(dateTimeVo);
        }

        String s = JSON.toJSONString(dateTimeList);
        System.out.println(s);
        return Result.updateResp(1, "数据获取成功","",s);
    }

    @Override
    public Result getConsInfoByIndex() {
        List<ConsultantFrontVo> consultantFrontVos = consultantMapper.getConsInfoByIndex();
        List<ConsultantFieldVo> consultantFieldVos = new ArrayList<>();
        for (ConsultantFrontVo vo : consultantFrontVos) {
            List<ConsultantFieldVo> query = consultantFieldMapper.query(vo.getId());
            vo.setConsultantFieldVos(query);
        }
        return new Result(0,"数据获取成功",consultantFrontVos);
    }

    @Override
    public Result getFieldList() {
        List<Field> query = fieldMapper.query();
        return new Result(0,"获取领域列表成功",query);
    }
}